/*
 * @Description: 新增元数据别名弹窗组件
 * @Author: Rfan
 * @Date: 2022-01-07 14:54:11
 * @LastEditTime: 2022-08-09 19:52:56
 */

import { useEffect } from 'react';
import { Button, Form, Modal } from 'antd';
import { useMetadataAliasContext } from '../../contexts/MetadataAliasContext';
import AliasForm from './AliasForm';
import type { FC } from 'react';
import type { ICommonDialog } from '@/interfaces/global';

interface addDialogProps extends ICommonDialog {}

class LanguageItem {
  language: string;

  name: string;

  constructor(language: string, name?: string) {
    this.language = language;
    this.name = name || '';
  }
}

const AddDialog: FC<addDialogProps> = (props) => {
  const { visible, onClose } = props;
  const { addAliasFunc } = useMetadataAliasContext();
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      form.setFieldsValue({
        languageList: [new LanguageItem('英语')]
      });
    }
  }, [visible]);

  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  /**
   * @description: 新增别名
   * @param {any} values 新增的别名
   */
  const onFinish = (values: any) => {
    values.languageList.unshift(new LanguageItem('中文', values.cname));
    console.log({ values });
    addAliasFunc(values).then(() => {
      onClose();
    });
  };

  /**
   * @description: 提交失败
   * @param {any} errorInfo 错误信息
   */
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  /**
   * @description: 关闭弹窗方法
   */
  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="新建元数据别名"
      visible={visible}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="confirm" type="primary" onClick={submitFunc}>
          保存
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        preserve={false}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <AliasForm />
      </Form>
    </Modal>
  );
};

export default AddDialog;
